import { useCallback, useEffect, useState } from "react";
import { message } from "antd";
import request from "@/utils/request";
import { stringify } from "qs";

import { usePolling } from "@/views/hooks/usePolling";

/**
 * 创建导入任务
 * @param {*} businessParam   "json字符串形式 "
 * @param {*} file   ⽂件
 * @param {*} taskType integer(
 * @returns {code,data:导⼊任务id ,msg }
 */
async function createImportTask(params) {
	return request(`/blade-log/taskInfo/createImportTask`, {
		method: "POST",
		data: params,
		loading: true
	});
}
/**
 * 确认导⼊/取消导⼊
 * @param {*} taskId   导⼊任务id
 * @param {*} type 执⾏类型 1:确认导⼊ 2:取消导⼊
 * @returns {code,data,msg,success }
 */
async function executeImportTask(params) {
	return request(`/blade-log/taskInfo/executeImportTask`, {
		method: "POST",
		data: params,
		loading: true
	});
}

/**
 * 获取导⼊任务进度(含预览)
 * @param {*} params {taskId}
 * @returns {code,data:{completed,failNum,successNum,totalNum,importedNum,taskId},msg,success}
 */
async function getImportTaskRate(params) {
	return request(`/blade-log/taskInfo/getImportTaskRate?${stringify(params)}`, {
		loading: false
	});
}

/**
 * 获取预览数据
 * @param {*} params {taskId}
 * @returns {code,data:{importPreviewErrorResult:{items[{rowIndex}],totalNum},importPreviewNormalResult:{items:[],totalNum,warningItems}},msg,success}
 */
async function getPreview(params) {
	return request(`/blade-log/taskInfo/getPreview?${stringify(params)}`, {
		loading: false
	});
}

/**
 * 下载⽂件
 * @param {*} params id
 * @returns {code,data,msg,success }
 */
async function downLoadFile(params) {
	return request(`/blade-log/taskInfo/downLoadFile?${stringify(params)}`, {
		method: "GET",
		// getResponse: true,
		// responseType: "blob",
		loading: true
	});
}
export const useImportTask = () => {
	const [step, setStep] = useState({
		first: null, //创建
		second: null, // 进度完成
		third: null, //预览
		fourth: null, //确认
		fifth: null //下载
	});
	const [taskId, setTaskId] = useState("");
	const [percent, setPercent] = useState(0);
	const [previewData, setPreviewData] = useState(null);

	const { setTimer, clearTimer } = usePolling();

	const handleDownload = useCallback(
		_id => {
			const API_DATA = { id: taskId };
			if (_id && (typeof _id === "string" || typeof _id === "number")) {
				API_DATA.id = _id;
			}
			downLoadFile(API_DATA).then(res => {
				console.log("任务下载，完成", res);
				setStep(pre => ({ ...pre, fifth: true }));
				const { data, msg: msg1, message: msg2 } = res;
				if (data && typeof data === "string" && String(data).startsWith("http")) {
					window.open(data);
				} else {
					message.error(msg1 || msg2 || "下载文件失败");
				}
			});
		},
		[taskId]
	);

	const handlePreview = useCallback(
		_id => {
			const API_DATA = { taskId: taskId };
			if (_id && (typeof _id === "string" || typeof _id === "number")) {
				API_DATA.taskId = _id;
			}
			getPreview(API_DATA).then(res => {
				const { code, data, msg: msg1, message: msg2, success } = res;
				console.log("任务预览，完成", res);
				if (success && data) {
					setPreviewData(data);
					setStep(pre => ({ ...pre, third: true }));
				} else {
					setPreviewData(null);
					setStep(pre => ({ ...pre, third: false }));
					message.error(msg1 || msg2 || "任务预览失败");
				}
			});
		},
		[taskId]
	);
	/**
	 * 确认导入 1:确认导⼊ 2:取消导⼊
	 */
	const handleExecuteTask = useCallback(
		({ taskId: _id, type }, callback) => {
			const API_DATA = {
				taskId,
				type
			};

			if (_id && (typeof _id === "string" || typeof _id === "number")) {
				API_DATA.taskId = _id;
			}

			executeImportTask(API_DATA).then(({ code, data, msg, success }) => {
				console.log("确认导入", type);
				if (success) {
					if (type == 1) {
						setStep(pre => ({ ...pre, fourth: true }));
					} else {
						setStep(pre => ({ ...pre, fourth: false }));
					}
					message.success(msg || "操作成功");
				} else {
					message.error(msg || "操作失败");
					setStep(pre => ({ ...pre, fourth: false }));
				}
				callback && callback({ code, data, msg, success });
			});
		},
		[taskId]
	);

	const startTask = useCallback(
		(params, callback) => {
			console.log("任务创建，开始");
			createImportTask(params).then(({ success, data: tid, msg: msg1, message: msg2 }) => {
				setTaskId(tid);

				if (success) {
					console.log("任务创建，完成");
					setStep(pre => ({ ...pre, first: true }));

					setTimer(getImportTaskRate, { taskId: tid }, ({ completed, importedNum, taskId, totalNum }) => {
						if (completed) {
							console.log("任务导入，完成 tid", tid);

							setStep(pre => ({ ...pre, second: true }));

							callback && callback(tid);

							return true;
						} else {
							console.log("任务导入，进行中");
							console.log("setPercent");
							setPercent((((importedNum || 0) / (totalNum || 1)) * 100).toFixed());
							return false;
						}
					});
				} else {
					setStep(pre => ({ ...pre, first: false }));
					message.warning(msg1 || msg2 || "任务创建失败");
				}
			});
		},
		[setTaskId]
	);

	/**
	 * 完整的下载步骤
	 * 创建任务，轮询进度，下载文件
	 * @param {*} params 导入参数
	 */
	const downloadTask = useCallback(
		params => {
			startTask(params, tid => handleDownload(tid));
		},
		[startTask, handleDownload]
	);

	/**
	 * 预览步骤
	 * 创建任务，轮询进度，预览文件
	 * @param {*} params 导入参数
	 */
	const startTaskAndPreview = useCallback(
		params => {
			startTask(params, tid => handlePreview(tid));
		},
		[startTask, handlePreview]
	);
	return {
		taskId, //导入任务id
		percent, // 导入进度
		setTimer, // 轮询任务
		clearTimer, //  取消轮询任务
		step, // 任务步骤
		handleDownload, // 下载文件
		startTask, // 开始任务 (需要手动调用handleDownload下载)
		downloadTask, // 开始任务(完整的下载步骤)
		startTaskAndPreview,
		handleExecuteTask,
		previewData // 预览数据
	};
};
